// import buy from '../../../wxjs/buy.js'
import Paging from '../../../wxjs/Paging.js'
const app = getApp();
var pag = new Paging();

var data = {
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  xbodyMsg: "请稍等...",
  price: 0, //单价
  totalPrice:0,//总价
  quantity: 1, //数量
  couponsAmount:0,
  couponId:null,
  lastPrice:0,
};

var currentPage = {
  data,
  listParams:{},
  form: {}, //详情请求参数
  orderParam: {},//订单请求参数
  payParam: {},//支付参数
  onLoad,
  onShow,
  getDetail,
  orderAdd,//添加订单
  wxPay,//微信支付前调用
  payment,//微信支付
  getCouponsList,//获取可用优惠券张数
  reduceCount,//数量减
  addCount,//数量加
  getTotalPrice,

  navToNext,
};

var page = Object.assign(pag.func(), currentPage);

Page(page);

function onLoad(options) {
  const that = this;
  const uuid = options && options.uuid || '';

  that.form.uuid = uuid;
  that.getDetail();
}

function onShow(){
  const that=this;
}

function reduceCount(){
  const that = this;
  let quantity = that.data.quantity || 1;
  if (quantity == 1) return false;
  quantity--;
  that.setData({
    quantity,
  })
  that.getTotalPrice();
}

function addCount() {
  const that = this;
  let quantity = that.data.quantity || 1;
  quantity++;
  that.setData({
    quantity,
  })
  that.getTotalPrice();
}

function getTotalPrice() {
  const that=this;
  let quantity = that.data.quantity || 1;
  let price = that.data.price || 0;
  var totalPrice = quantity * (Number(price) * 10000) / 10000;
  var lastPrice = 0;
  if (that.data.amount){
    lastPrice = (totalPrice * 1 - that.data.amount * 1).toFixed(2);
  }else{
    lastPrice = totalPrice;
  }

  that.setData({
    totalPrice,
    lastPrice
  })
  that.getCouponsList();
}

function getCouponsList() {
  const that = this;
  let listParams = {};
  listParams.status = 0;
  listParams.lectureUuid = that.form.uuid;
  listParams.pageNum = 1; //当前页数
  listParams.pageSize = 99999; //1页的条数
  listParams.orderAmount = that.data.totalPrice; //1页的条数

  app.middleware.requestAjax({
    serAddr: app.serAddrs.getUsedCoupon,
    data: listParams,
    cancelToast: true,
    success: function (res) {
      that.setData({
        lists: res.data || []
      })
    },
    fail: function (res) {
      that.setData({
        lists: []
      })
    }
  })
}

function getDetail() {
  const that = this;

  app.middleware.requestAjax({
    serAddr: app.serAddrs.getLectureDetail,
    data: that.form,
    cancelToast: true,
    success: function(res) {
      let xbody = res.data;
      let validityDate = app.middleware.time(0, xbody.validityDate);
      xbody.time = validityDate.typeA;
      xbody.week = `(周${validityDate.weekText})`;

      that.setData({
        xbodyMsg: "",
        xbody,
        price: xbody.price,
        totalPrice: xbody.price,
        lastPrice:xbody.price
      })
      that.getCouponsList();
    },
    fail: function(res) {
      that.setData({
        xbodyMsg: res && res.msg || "请求失败"
      })
    }
  })
}

function orderAdd() {
  const that = this;
  const uuid = that.data.xbody.uuid || '';
  let quantity = that.data.quantity || 1;
  let price = that.data.price || 0;
  let totalPrice = that.data.totalPrice || 0;

  if (totalPrice == 0) return false;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  that.orderParam.tOrders = [];
  that.orderParam.tOrders.push({
    lectureUuid: uuid,
    orderPrice: price,
    orderQuantity: quantity,
    retailor: "", //返利人userid
    status: "0", //状态
    couponUserId:that.data.couponId,
  })
  app.middleware.requestAjax({
    serAddr: app.serAddrs.orderAdd,
    data: that.orderParam,
    success: function(ores) {

      that.payParam.uuids = ores.data;
      that.payParam.orderUuids = ores.data.join(",");

      that.wxPay();

    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })
}

function wxPay() {
  const that = this;
  
  app.middleware.requestAjax({
    serAddr: app.serAddrs.wxPay,
    header:{
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: {
      orderUuids: that.payParam.orderUuids,
    },
    cancelToast: true,
    success: function(res) {
      that.payment(res.data)
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })

}

function payment(data) {
  const that = this;

  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      app.infoLog(res)
    },
    fail(res) {
      app.infoLog(res)
    },
    complete: function(res) {
      app.infoLog(res)
      app.isToOrder = true;
      wx.switchTab({
        url: app.xhx_route.mineBase,
      })
    }
  })
}

function navToNext(event) {
  const that = this;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  let params = event.currentTarget.dataset;
  const url = params.url;
  const unskip = params.unskip;
  if (unskip) return false;
  wx.navigateTo({
    url: `${app.xhx_route[url]}?${paramFormat(params)}`,
  })

}

function paramFormat(params) {
  let url = '';
  for (let key in params) {
    if (key == 'url' || key == 'unskip') continue;
    if (url) url += `&`;
    url += `${key}=${params[key] || ''}`
  }

  return url;
}